import os
from src.config import IMAGE_DIR
from src.database.dao_factory import DAOFactory
from src.utils.logger import log_error


class FootballController:
    def __init__(self):
        self.dao_factory = DAOFactory.get_instance()
   
    
    def upload_football_icons(self, icon_file, icon_type, icon_filename, icon_fileext):
        """
        上传足球图标文件到指定目录
        
        :param icon_file: 上传的图标文件对象
        :param file_type: 图标类型（如球队、球员等）
        :return: 处理结果
        """
        try:
            target_directory = os.path.join(IMAGE_DIR, "football_icons", icon_type)
            if not os.path.exists(target_directory):
                os.makedirs(target_directory, exist_ok=True)
            
            filename = icon_filename
            path = os.path.join(target_directory, filename +"."+ icon_fileext)
            icon_file.save(path)
            self.dao_factory.get_uploaded_file_dao().create_football_icon(
                icon_path=path,
                icon_filename=filename,
                icon_type=icon_type
            )
        except Exception as e:
            log_error(f"上传足球图标文件时出错: {e}")
            return {"success": False, "message": str(e)}
        return {"success": True, "message": "足球图标文件上传成功", "icon_path": path}
    
    def update_football_icon_filename(self, icon_id, icon_filename):
        """
        更新足球图标文件名
        
        :param icon_id: 图标ID
        :param icon_filename: 新的图标文件名
        :return: 处理结果
        """
        try:    
            result = self.dao_factory.get_uploaded_file_dao().update_football_icon_filename(
                icon_id=icon_id,
                icon_filename=icon_filename
            )
            return result
        except Exception as e:
            raise Exception(f"更新足球图标文件名时出错: {e}")    
        
    def get_football_icons(self, icon_type, page=1, page_size=10):
        """
        获取指定类型的足球图标列表
        
        :param icon_type: 图标类型（如球队、球员等）
        :param page: 页码
        :param page_size: 每页数量
        :return: 图标列表和总数
        """
        try:
            records, total_count = self.dao_factory.get_uploaded_file_dao().get_football_icons(
                icon_type=icon_type,
                page=page,
                page_size=page_size
            )

            total_pages = (total_count + page_size - 1) // page_size
            
            return {
                "items": records,
                "pagination": {
                    "page": page,
                    "page_size": page_size,
                    "total_count": total_count,
                    "total_pages": total_pages
                },
            }
        except Exception as e:
            log_error(f"获取足球图标时出错: {e}")
            raise Exception(f"获取足球图标时出错: {e}")
        
    def delete_football_icon(self, icon_id):
        """
        删除指定类型的足球图标
        
        :param icon_id: 图标ID
        :return: 处理结果
        """
        try:
            result = self.dao_factory.get_uploaded_file_dao().delete_football_icon(icon_id)
            path = result.file_path
            if os.path.exists(path):
                os.remove(path)
            return {"success": True, "message": "图标删除成功"}
        except Exception as e:
            log_error(f"删除足球图标时出错: {e}")
            return {"success": False, "message": str(e)}
        
        
        
    def generate_icon_videos(self, video_paths, subtitle_id):
        """
        生成足球图标视频
        
        :param video_folder: 视频文件夹路径
        :param subtitle_path: 字幕文件路径
        :return: 处理结果
        """
        try:
            # 创建图标视频生成器
            from src.modules.football_icon_video_generator import FootballIconVideoGenerator
            
            # 使用图标目录
            icons_base_dir = os.path.join(IMAGE_DIR, "football_icons")
            generator = FootballIconVideoGenerator(icons_base_dir=icons_base_dir)
            subtitle_path = self.dao_factory.get_uploaded_file_dao().get_by_id(subtitle_id).file_path
            # 解析字幕并生成视频
            results, count = generator.parse_and_generate(video_paths, subtitle_path)
            video_paths = []
            icon_video_paths = []
            for result in results:
                video_paths.append(result["video_path"])
                icon_video_paths.append(result["output_path"])
            mappings = [{
                "subtitle_path": subtitle_path,
                "video_paths": video_paths,
                "icon_video_paths": icon_video_paths
            }]
                
            self.dao_factory.get_uploaded_file_dao().update_subtitle_videos_mappings(mappings)
            return results
            
        except Exception as e:
            error_message = f"生成足球图标视频时发生错误: {str(e)}"
            raise Exception(error_message)